<template>
  <div class="rayfile-container">
    <!-- 顶部工具栏 -->
    <div class="rayfile-header">
      <div class="header-left">
        <h1>共享网盘</h1>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/rayfile' }">我的网盘</el-breadcrumb-item>
          <el-breadcrumb-item v-for="(item, index) in currentPath" :key="index">
            {{ item.name }}
          </el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="header-actions">
        <el-button-group>
          <el-button @click="handleBack" :disabled="currentPath.length === 0">
            <el-icon><Back /></el-icon>
            返回上级
          </el-button>
          <el-button @click="handleRefresh">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </el-button-group>
        <el-button-group>
          <el-dropdown trigger="hover" @command="handleUploadCommand">
            <el-button type="primary">
              <el-icon><Upload /></el-icon>
              上传文件
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="single">上传单个文件</el-dropdown-item>
                <el-dropdown-item command="multiple">上传多个文件</el-dropdown-item>
                <el-dropdown-item command="folder">上传文件夹</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-button type="success" @click="handleNewFolder">
            <el-icon><FolderAdd /></el-icon>
            新建文件夹
          </el-button>
          <el-button :type="selectionMode ? 'danger' : 'default'" @click="toggleSelectionMode">
            <el-icon><Select /></el-icon>
            {{ selectionMode ? '退出多选' : '多选模式' }}
          </el-button>
          <el-button type="danger" @click="handleBatchDelete" :disabled="selectedFiles.length === 0" v-show="selectionMode">
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
        </el-button-group>
        <el-button-group>
          <el-button @click="viewMode = 'list'" :type="viewMode === 'list' ? 'primary' : ''">
            <el-icon><List /></el-icon>
          </el-button>
          <el-button @click="viewMode = 'grid'" :type="viewMode === 'grid' ? 'primary' : ''">
            <el-icon><Grid /></el-icon>
          </el-button>
        </el-button-group>
      </div>
    </div>

    <!-- 文件列表区域 -->
    <div class="rayfile-content" :class="{ 'grid-view': viewMode === 'grid' }">
      <!-- 列表视图 -->
      <template v-if="viewMode === 'list'">
        <el-table 
          ref="fileTable"
          :data="fileList" 
          style="width: 100%"
          height="calc(100vh - 210px)"
          @row-contextmenu="handleContextMenu"
          @row-dblclick="handleRowDblClick"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" v-if="selectionMode" />
          <el-table-column prop="name" label="文件名" min-width="200">
            <template #default="{ row }">
              <div class="file-item">
                <el-icon v-if="row.type === 'folder'" class="folder-icon"><Folder /></el-icon>
                <el-icon v-else class="file-icon" :class="getFileIconClass(row.name)">
                  <component :is="getFileIcon(row.name)" />
                </el-icon>
                <span>{{ row.name }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="大小" width="120" sortable>
            <template #default="{ row }">
                <span v-if="row.size > 0 && row.size < 1024"> {{ row.size }}B</span>
                <span v-else-if="row.size >= 1024 && row.size < 1024 * 1024"> {{ (row.size / 1024).toFixed(2) }}KB</span>
               <span v-else-if="row.size > 1024 * 1024 && row.size < 1024 * 1024 * 1024"> {{ (row.size / 1024 / 1024).toFixed(2) }}MB</span>
               <span v-else-if="row.size >= 1024 * 1024 * 1024 && row.size < 1024 * 1024 * 1024 * 1024"> {{ (row.size / 1024 / 1024 / 1024).toFixed(2) }}GB</span>
               <span v-else-if="row.size >= 1024 * 1024 * 1024 * 1024"> {{ (row.size / 1024 / 1024 / 1024 / 1024).toFixed(2) }}KB</span>
               <span v-else> - </span>
            </template>
          </el-table-column>
          <el-table-column prop="modifyDateStr" label="修改时间" width="180" sortable>
            <template #default="{ row }">
                <span v-if="row.modifyDateStr != '' && row.modifyDateStr != null"> {{ row.modifyDateStr }}</span>
                <span v-else> -</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="{ row }">
              <el-button-group>
                <el-button type="primary" link @click="handleDownload(row)" :disabled="row.dir">
                  下载
                </el-button>
                <el-button type="primary" link @click="handleMove(row)">
                  移动
                </el-button>
                <el-button type="primary" link @click="handleRename(row)">
                  重命名
                </el-button>
                <el-button type="danger" link @click="handleDelete(row)">
                  删除
                </el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
      </template>

      <!-- 网格视图 -->
      <template v-else>
        <div class="grid-container">
          <div 
            v-for="item in fileList" 
            :key="item.name"
            class="grid-item"
            @contextmenu.prevent="handleContextMenu(item)"
            @dblclick="handleRowDblClick(item)"
          >
            <el-icon v-if="item.type === 'folder'" class="folder-icon"><Folder /></el-icon>
            <el-icon v-else class="file-icon" :class="getFileIconClass(item.name)">
              <component :is="getFileIcon(item.name)" />
            </el-icon>
            <span class="grid-item-name">{{ item.name }}</span>
          </div>
        </div>
      </template>
    </div>

    <!-- 上传文件对话框 -->
    <el-dialog v-model="uploadDialogVisible" :title="getUploadTitle" width="500px">
      <el-upload
        class="upload-demo"
        drag
        action="/api/upload"
        :multiple="uploadType === 'multiple'"
        :webkitdirectory="uploadType === 'folder'"
        :on-progress="handleUploadProgress"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          {{ getUploadText }}
        </div>
        <template #tip>
          <div class="el-upload__tip">
            {{ getUploadTip }}
          </div>
        </template>
      </el-upload>
    </el-dialog>

    <!-- 新建文件夹对话框 -->
    <el-dialog v-model="folderDialogVisible" title="新建文件夹" width="400px">
      <el-form :model="folderForm" label-width="80px">
        <el-form-item label="文件夹名称">
          <el-input v-model="folderForm.name" placeholder="请输入文件夹名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="folderDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="createFolder">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 右键菜单 -->
    <div v-show="contextMenuVisible" :style="contextMenuStyle" class="context-menu">
      <div class="context-menu-item" @click="handleDownload(contextMenuTarget)">
        <el-icon><Download /></el-icon>
        <span>下载</span>
      </div>
      <div class="context-menu-item" @click="handleMove(contextMenuTarget)">
        <el-icon><Position /></el-icon>
        <span>移动</span>
      </div>
      <div class="context-menu-item" @click="handleRename(contextMenuTarget)">
        <el-icon><Edit /></el-icon>
        <span>重命名</span>
      </div>
      <div class="context-menu-item" @click="handleDelete(contextMenuTarget)">
        <el-icon><Delete /></el-icon>
        <span>删除</span>
      </div>
    </div>

    <!-- 文件预览对话框 -->
    <el-dialog v-model="previewDialogVisible" :title="previewFile.name" width="80%">
      <div class="preview-container">
        <!-- 图片预览 -->
        <img v-if="isImage(previewFile.name)" :src="previewFile.url" class="preview-image" />
        <!-- 视频预览 -->
        <video v-else-if="isVideo(previewFile.name)" :src="previewFile.url" controls class="preview-video">
          您的浏览器不支持视频播放
        </video>
        <!-- PDF预览 -->
        <iframe v-else-if="isPDF(previewFile.name)" :src="previewFile.url" class="preview-pdf"></iframe>
        <!-- Office文档预览 -->
        <iframe v-else-if="isOffice(previewFile.name)" :src="`https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(previewFile.url)}`" class="preview-office"></iframe>
        <!-- 音频预览 -->
        <audio v-else-if="isAudio(previewFile.name)" :src="previewFile.url" controls class="preview-audio">
          您的浏览器不支持音频播放
        </audio>
        <!-- 代码文件预览 -->
        <div v-else-if="isCode(previewFile.name)" class="preview-code">
          <pre><code>{{ previewFile.content }}</code></pre>
        </div>
        <!-- 文本预览 -->
        <div v-else-if="isText(previewFile.name)" class="preview-text">
          {{ previewFile.content }}
        </div>
        <!-- 其他文件类型 -->
        <div v-else class="preview-unsupported">
          <el-icon><Document /></el-icon>
          <p>该文件类型暂不支持预览</p>
        </div>
      </div>
    </el-dialog>

    <!-- 分享文件对话框 -->
    <el-dialog v-model="shareDialogVisible" title="分享文件" width="500px">
      <div class="share-dialog-content">
        <div v-if="shareInfo.url" class="share-link">
          <el-input v-model="shareInfo.url" readonly>
            <template #append>
              <el-button @click="copyShareLink">复制链接</el-button>
            </template>
          </el-input>
          <div class="share-expiry">
            <span>链接有效期：{{ shareInfo.expiryTime || '永久有效' }}</span>
          </div>
        </div>
        <div v-else class="share-options">
          <el-form :model="shareForm" label-width="100px">
            <el-form-item label="有效期">
              <el-select v-model="shareForm.expiry" placeholder="请选择有效期">
                <el-option label="1天" value="1" />
                <el-option label="7天" value="7" />
                <el-option label="30天" value="30" />
                <el-option label="永久有效" value="-1" />
              </el-select>
            </el-form-item>
            <el-form-item label="访问密码">
              <el-input v-model="shareForm.password" placeholder="可选，留空则不设置密码" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="shareDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="generateShareLink" v-if="!shareInfo.url">生成链接</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 下载进度对话框 -->
    <el-dialog v-model="downloadProgressVisible" title="下载进度" width="400px" :close-on-click-modal="false" :show-close="true">
      <div class="download-progress">
        <el-progress :percentage="downloadProgress" :status="downloadStatus" />
        <div class="download-info">
          <span>{{ downloadFileName }}</span>
          <span>{{ downloadSpeed }}</span>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDownloadDialog">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 重命名对话框 -->
    <el-dialog v-model="renameDialogVisible" title="重命名" width="400px">
      <el-form :model="renameForm" label-width="80px">
        <el-form-item label="新名称">
          <el-input v-model="renameForm.name" placeholder="请输入新名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="renameDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmRename">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 移动文件对话框 -->
    <el-dialog v-model="moveDialogVisible" title="移动文件" width="500px">
      <div class="move-dialog-content">
        <div class="current-path">
          <span>当前位置：</span>
          <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/rayfile' }">我的网盘</el-breadcrumb-item>
            <el-breadcrumb-item v-for="(item, index) in moveTargetPath" :key="index">
              {{ item.name }}
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <div class="folder-list">
          <div 
            v-for="item in moveFolderList" 
            :key="item.name"
            class="folder-item"
            @click="handleMoveFolderClick(item)"
          >
            <el-icon><Folder /></el-icon>
            <span>{{ item.name }}</span>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="moveDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmMove">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'
import { 
  Upload, 
  FolderAdd, 
  Folder, 
  Document,
  UploadFilled,
  Back,
  Refresh,
  List,
  Grid,
  Download,
  Share,
  Edit,
  Delete,
  Picture,
  VideoPlay,
  Headset,
  Files,
  Select,
  Position
} from '@element-plus/icons-vue'

export default {
  name: 'RayFile',
  components: {
    Upload,
    FolderAdd,
    Folder,
    Document,
    UploadFilled,
    Back,
    Refresh,
    List,
    Grid,
    Download,
    Share,
    Edit,
    Delete,
    Picture,
    VideoPlay,
    Headset,
    Files,
    Select,
    Position
  },
  data() {
    return {
      viewMode: 'list',
      currentPath: [],
      fileList: [],
      selectedFiles: [],
      selectionMode: false,
      uploadDialogVisible: false,
      folderDialogVisible: false,
      previewDialogVisible: false,
      renameDialogVisible: false,
      folderForm: {
        name: ''
      },
      renameForm: {
        name: ''
      },
      renameTarget: null,
      contextMenuVisible: false,
      contextMenuStyle: {
        left: '0px',
        top: '0px'
      },
      contextMenuTarget: null,
      previewFile: {
        name: '',
        url: '',
        content: ''
      },
      buckName : 'rayfile',
      shareDialogVisible: false,
      shareForm: {
        expiry: '7',
        password: ''
      },
      shareInfo: {
        url: '',
        expiryTime: ''
      },
      downloadProgressVisible: false,
      downloadProgress: 0,
      downloadStatus: '',
      downloadFileName: '',
      downloadSpeed: '',
      uploadType: 'single',
      moveDialogVisible: false,
      moveTarget: null,
      moveTargetPath: [],
      moveFolderList: []
    }
  },
  mounted() {
    // 点击其他地方关闭右键菜单
    document.addEventListener('click', () => {
      this.contextMenuVisible = false
    })
  },
  beforeUnmount() {
    // 移除事件监听
    document.removeEventListener('click', () => {
      this.contextMenuVisible = false
    })
  },
  created(){
    this.getFileList('')
  },
  methods: {
    getFileList(pathName){//获取目录下的文件列表
        this.$get('/getFileList',{
            buckName : this.buckName,
            pathName : pathName
        }).then(res=>{
            if (res.code == 200) {
                // 处理返回的数据，将dir字段映射为type
                this.fileList = res.data.map(item => ({
                    ...item,
                    type: item.dir ? 'folder' : 'file'
                }))
            }else{
                ElMessage.error(res.msg)
            }
        }).catch(err=>{
            console.log(err)
        })
    },
    getFileIcon(fileName) {
      const extension = fileName.split('.').pop().toLowerCase()
      const iconMap = {
        jpg: Picture,
        jpeg: Picture,
        png: Picture,
        gif: Picture,
        mp4: VideoPlay,
        mp3: Headset,
        txt: Document,
        pdf: Document,
        doc: Document,
        docx: Document,
        xls: Document,
        xlsx: Document,
        default: Files
      }
      return iconMap[extension] || iconMap.default
    },
    getFileIconClass(fileName) {
      const extension = fileName.split('.').pop().toLowerCase()
      return `file-icon-${extension}`
    },
    isImage(fileName) {
      const extension = fileName.split('.').pop().toLowerCase()
      return ['jpg', 'jpeg', 'png', 'gif'].includes(extension)
    },
    isText(fileName) {
      const extension = fileName.split('.').pop().toLowerCase()
      return ['txt', 'md', 'json', 'js', 'css', 'html'].includes(extension)
    },
    isVideo(fileName) {
      const extension = fileName.split('.').pop().toLowerCase()
      return ['mp4', 'webm', 'ogg', 'mov'].includes(extension)
    },
    isPDF(fileName) {
      const extension = fileName.split('.').pop().toLowerCase()
      return extension === 'pdf'
    },
    isOffice(fileName) {
      const extension = fileName.split('.').pop().toLowerCase()
      return ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'].includes(extension)
    },
    isAudio(fileName) {
      const extension = fileName.split('.').pop().toLowerCase()
      return ['mp3', 'wav', 'ogg', 'm4a'].includes(extension)
    },
    isCode(fileName) {
      const extension = fileName.split('.').pop().toLowerCase()
      return ['js', 'jsx', 'ts', 'tsx', 'vue', 'html', 'css', 'scss', 'less', 'json', 'xml', 'yaml', 'yml', 'md', 'py', 'java', 'c', 'cpp', 'go', 'php', 'rb', 'sh'].includes(extension)
    },
    handleBack() {
      if (this.currentPath.length > 0) {

        this.currentPath.pop()

        // 获取上一级路径
        if (this.currentPath == null || this.currentPath.length == 0) {
          this.getFileList('')
        } else {

          if (this.currentPath[this.currentPath.length - 1].lastPath == null || this.currentPath[this.currentPath.length - 1].lastPath == '') {
            this.getFileList(this.currentPath[this.currentPath.length - 1].name + '/')
          } else {
            this.getFileList(this.currentPath[this.currentPath.length - 1].lastPath + '/' + this.currentPath[this.currentPath.length - 1].name + '/')
          }
        }
      }
    },
    handleRefresh() {
      // 获取当前路径  
      if (this.currentPath == null || this.currentPath.length == 0) {
        this.getFileList('')
      } else {

        if (this.currentPath[this.currentPath.length - 1].lastPath == null || this.currentPath[this.currentPath.length - 1].lastPath == '') {
          this.getFileList(this.currentPath[this.currentPath.length - 1].name + '/')
        } else {
          this.getFileList(this.currentPath[this.currentPath.length - 1].lastPath + '/' + this.currentPath[this.currentPath.length - 1].name + '/')
        }
      }
      
      // ElMessage.success('刷新成功')
    },
    handleUploadCommand(command) {
      switch (command) {
        case 'single':
          this.uploadDialogVisible = true
          this.uploadType = 'single'
          break
        case 'multiple':
          this.uploadDialogVisible = true
          this.uploadType = 'multiple'
          break
        case 'folder':
          this.uploadDialogVisible = true
          this.uploadType = 'folder'
          break
      }
    },
    handleNewFolder() {
      this.folderDialogVisible = true
    },
    createFolder() {
      if (!this.folderForm.name) {
        ElMessage.warning('请输入文件夹名称')
        return
      }
      
      let req = {
        bucketName : this.buckName,
        name : this.folderForm.name,
        lastPath : '',
      }
      if (this.currentPath == null || this.currentPath.length == 0) {
        req.lastPath = ''
      } else {

        if (this.currentPath[this.currentPath.length - 1].lastPath == null || this.currentPath[this.currentPath.length - 1].lastPath == '') {
          req.lastPath = this.currentPath[this.currentPath.length - 1].name + '/'
        } else {
          req.lastPath = this.currentPath[this.currentPath.length - 1].lastPath + '/' + this.currentPath[this.currentPath.length - 1].name + '/'
        }
      }
      // TODO: 调用创建文件夹API
      this.$post('/createFolder',req).then(res =>{
        if (res.code == 200) {
          this.folderDialogVisible = false
          ElMessage.success(res.msg)
          this.handleRefresh()
        }else{
          ElMessage.error(res.msg)
        }
      }).catch(err =>{
        console.log(err);
        
      })
      
    },
    handleDownload(row) {
      this.downloadFileName = row.name
      this.downloadProgressVisible = true
      this.downloadProgress = 0
      this.downloadStatus = ''
      this.downloadSpeed = '准备下载...'

      // 定义分片大小（5MB）
      const chunkSize = 5 * 1024 * 1024
      let start = 0
      let end = chunkSize
      let chunks = []
      let totalSize = row.size
      let downloadedSize = 0
      let startTime = new Date().getTime()
      let lastLoaded = 0
      let lastTime = startTime

      const downloadChunk = () => {
        if (start >= totalSize) {
          // 所有分片下载完成，合并文件
          const blob = new Blob(chunks, { type: 'application/octet-stream' })
          const link = document.createElement('a')
          link.href = window.URL.createObjectURL(blob)
          link.download = row.name
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          window.URL.revokeObjectURL(link.href)
          
          this.downloadStatus = 'success'
          setTimeout(() => {
            this.downloadProgressVisible = false
          }, 1000)
          return
        }

        // 计算当前分片的结束位置
        end = Math.min(start + chunkSize, totalSize)

        // 创建新的XMLHttpRequest
        const xhr = new XMLHttpRequest()
        xhr.open('GET', row.url, true)
        xhr.setRequestHeader('Range', `bytes=${start}-${end-1}`)
        xhr.responseType = 'blob'

        xhr.onload = () => {
          if (xhr.status === 206) { // 206 Partial Content
            chunks.push(xhr.response)
            downloadedSize += xhr.response.size
            start = end

            // 更新进度
            const percentCompleted = Math.round((downloadedSize * 100) / totalSize)
            this.downloadProgress = percentCompleted

            // 计算下载速度
            const currentTime = new Date().getTime()
            const timeDiff = (currentTime - lastTime) / 1000 // 转换为秒
            const loadedDiff = downloadedSize - lastLoaded
            
            if (timeDiff > 0) {
              const speed = loadedDiff / 1024 / 1024 / timeDiff // MB/s
              this.downloadSpeed = `${speed.toFixed(2)} MB/s`
            }

            lastLoaded = downloadedSize
            lastTime = currentTime

            // 继续下载下一个分片
            downloadChunk()
          } else {
            this.downloadStatus = 'exception'
            this.downloadSpeed = '下载失败'
            ElMessage.error('下载失败，请重试')
          }
        }

        xhr.onerror = () => {
          this.downloadStatus = 'exception'
          this.downloadSpeed = '下载失败'
          ElMessage.error('下载失败，请重试')
        }

        xhr.send()
      }

      // 开始下载第一个分片
      downloadChunk()
    },
    handleShare(row) {
      this.shareDialogVisible = true
      this.shareInfo = {
        url: '',
        expiryTime: ''
      }
      this.shareForm = {
        expiry: '7',
        password: ''
      }
    },
    generateShareLink() {
      // 构建文件路径
      let filePath = ''
      if (this.currentPath.length > 0) {
        const path = this.currentPath.map(item => item.name).join('/')
        filePath = `${path}/${this.contextMenuTarget.name}`
      } else {
        filePath = this.contextMenuTarget.name
      }

      // 调用分享API
      this.$post('/share', {
        buckName: this.buckName,
        pathName: filePath,
        expiry: this.shareForm.expiry,
        password: this.shareForm.password
      }).then(res => {
        if (res.code === 200) {
          this.shareInfo = {
            url: res.data.url,
            expiryTime: this.getExpiryTimeText(this.shareForm.expiry)
          }
          ElMessage.success('分享链接生成成功')
        } else {
          ElMessage.error(res.msg || '生成分享链接失败')
        }
      }).catch(err => {
        ElMessage.error('生成分享链接失败')
      })
    },
    copyShareLink() {
      navigator.clipboard.writeText(this.shareInfo.url).then(() => {
        ElMessage.success('链接已复制到剪贴板')
      }).catch(() => {
        ElMessage.error('复制失败，请手动复制')
      })
    },
    getExpiryTimeText(expiry) {
      if (expiry === '-1') return '永久有效'
      const date = new Date()
      date.setDate(date.getDate() + parseInt(expiry))
      return date.toLocaleDateString()
    },
    handleDelete(row) {
      // TODO: 实现文件删除逻辑
      this.$msgbox.confirm(
        '删除文件？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(()=>{
        let reqList = []
        reqList.push(row)
        this.$post('/deleteFiles',reqList).then(res =>{
          if (res.code == 200) {
            this.handleRefresh();
            this.$message.success(res.msg)
          }else{
            this.handleRefresh();
            this.$message.error(res.msg)
          }
        }).catch(err =>{
          console.log(err);
          
        })
      })
      
    },
    handleRename(row) {
      this.renameTarget = row
      this.renameForm.name = row.name
      this.renameDialogVisible = true
    },
    confirmRename() {
      if (!this.renameForm.name) {
        ElMessage.warning('请输入新名称')
        return
      }
      // 构建文件路径
      let filePath = ''
      if (this.currentPath.length > 0) {
        const path = this.currentPath.map(item => item.name).join('/')
        filePath = `${path}/${this.renameTarget.name}`
      } else {
        filePath = this.renameTarget.name
      }
      
      // if (filePath[0] != '/') {
      //   filePath = '/' + filePath
      // }
      if (this.renameTarget.dir) {
        if(filePath[filePath.length] != '/'){
          filePath = filePath + '/'
        }
        
      }

      // 构建新文件路径
      let newFilePath = ''
      if (this.currentPath.length > 0) {
        const path = this.currentPath.map(item => item.name).join('/')
        newFilePath = `${path}/${this.renameForm.name}`
      } else {
        newFilePath = this.renameForm.name
      }
     
      // if (newFilePath[0] != '/') {
      //   newFilePath = '/' + newFilePath
      // }
      if (this.renameTarget.dir) {
        if(newFilePath[newFilePath.length] != '/'){
          newFilePath = newFilePath + '/'
        }
        
      }

      // 调用重命名API
      this.$get('/renameFile', {
        buckName: this.buckName,
        oldPath: filePath,
        newPath: newFilePath
      }).then(res => {
        if (res.code === 200) {
          ElMessage.success('重命名成功')
          this.renameDialogVisible = false
          // 刷新文件列表
          this.handleRefresh()
        } else {
          ElMessage.error(res.msg || '重命名失败')
        }
      }).catch(err => {
        ElMessage.error('重命名失败')
      })
    },
    handleContextMenu(row, event) {
      if (event) {
        this.contextMenuStyle = {
          left: event.clientX + 'px',
          top: event.clientY + 'px'
        }
      }
      this.contextMenuTarget = row
      this.contextMenuVisible = true
    },
    handleRowDblClick(row) {
      if (row.dir) {
        this.currentPath.push(row)
        // 加载文件夹内容
        if (row.lastPath == null || row.lastPath == '') {
          this.getFileList(row.name + '/')
        }else{
          this.getFileList(row.lastPath + '/' + row.name + '/')
        }
        
      } else {
        this.previewFile = row
        this.previewDialogVisible = true
      }
    },
    handleUploadProgress(event, file) {
      console.log('上传进度：', event.percent)
    },
    handleUploadSuccess(response, file) {
      ElMessage.success('上传成功')
      // TODO: 刷新文件列表
    },
    handleUploadError(error, file) {
      ElMessage.error('上传失败')
    },
    closeDownloadDialog() {
      this.downloadProgressVisible = false
      this.downloadProgress = 0
      this.downloadStatus = ''
      this.downloadSpeed = ''
    },
    getUploadTitle() {
      switch (this.uploadType) {
        case 'single':
          return '上传单个文件'
        case 'multiple':
          return '上传多个文件'
        case 'folder':
          return '上传文件夹'
        default:
          return '上传文件'
      }
    },
    getUploadText() {
      switch (this.uploadType) {
        case 'single':
          return '将文件拖到此处，或点击上传'
        case 'multiple':
          return '将文件拖到此处，或点击上传'
        case 'folder':
          return '将文件夹拖到此处，或点击上传'
        default:
          return '将文件拖到此处，或点击上传'
      }
    },
    getUploadTip() {
      switch (this.uploadType) {
        case 'single':
          return '支持任意类型文件上传'
        case 'multiple':
          return '支持任意类型文件上传'
        case 'folder':
          return '支持任意类型文件夹上传'
        default:
          return '支持任意类型文件上传'
      }
    },
    handleSelectionChange(selection) {
      this.selectedFiles = selection
    },
    handleBatchDelete() {
      if (this.selectedFiles.length === 0) {
        ElMessage.warning('请选择要删除的文件')
        return
      }

      this.$msgbox.confirm(
        `确定要删除选中的 ${this.selectedFiles.length} 个文件吗？`,
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        let reqList = this.selectedFiles
        this.$post('/deleteFiles', reqList).then(res => {
          if (res.code == 200) {
            this.handleRefresh()
            this.$message.success(res.msg)
          } else {
            this.handleRefresh()
            this.$message.error(res.msg)
          }
        }).catch(err => {
          console.log(err)
        })
      })
    },
    toggleSelectionMode() {
      this.selectionMode = !this.selectionMode
      if (!this.selectionMode) {
        // 退出多选模式时清空选择
        this.selectedFiles = []
        // 清空表格的选择状态
        this.$refs.fileTable.clearSelection()
      }
    },
    handleMove(row) {
      this.moveTarget = row
      this.moveTargetPath = []
      this.moveDialogVisible = true
      this.loadMoveFolders('')
    },
    loadMoveFolders(path) {
      this.$get('/getFileList', {
        buckName: this.buckName,
        pathName: path
      }).then(res => {
        if (res.code == 200) {
          // 只显示文件夹
          this.moveFolderList = res.data.filter(item => item.dir)
        } else {
          ElMessage.error(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    },
    handleMoveFolderClick(folder) {
      this.moveTargetPath.push(folder)
      // 加载子文件夹
      let path = ''
      if (folder.lastPath) {
        path = folder.lastPath + '/' + folder.name + '/'
      } else {
        path = folder.name + '/'
      }
      this.loadMoveFolders(path)
    },
    confirmMove() {
      if (!this.moveTarget) {
        ElMessage.warning('请选择要移动的文件')
        return
      }

      // 构建源文件路径
      let sourcePath = ''
      if (this.currentPath.length > 0) {
        const path = this.currentPath.map(item => item.name).join('/')
        sourcePath = `${path}/${this.moveTarget.name}`
      } else {
        sourcePath = this.moveTarget.name
      }

      // 构建目标路径
      let targetPath = ''
      if (this.moveTargetPath.length > 0) {
        const path = this.moveTargetPath.map(item => item.name).join('/')
        targetPath = `${path}/${this.moveTarget.name}`
      } else {
        targetPath = this.moveTarget.name
      }

      // 调用移动API
      this.$get('/moveFile', {
        buckName: this.buckName,
        sourcePath: sourcePath,
        targetPath: targetPath
      }).then(res => {
        if (res.code === 200) {
          ElMessage.success('移动成功')
          this.moveDialogVisible = false
          // 刷新文件列表
          this.handleRefresh()
        } else {
          ElMessage.error(res.msg || '移动失败')
        }
      }).catch(err => {
        ElMessage.error('移动失败')
      })
    }
  }
}
</script>

<style scoped>
.rayfile-container {
  padding: 20px;
  height: calc(100vh - 100px);
  display: flex;
  flex-direction: column;
}

.rayfile-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.rayfile-content {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  overflow: auto;
}

.file-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.folder-icon {
  color: #e6a23c;
  font-size: 20px;
}

.file-icon {
  font-size: 20px;
}

.file-icon-jpg,
.file-icon-jpeg,
.file-icon-png,
.file-icon-gif {
  color: #67c23a;
}

.file-icon-mp4 {
  color: #f56c6c;
}

.file-icon-mp3 {
  color: #409eff;
}

.file-icon-txt,
.file-icon-pdf,
.file-icon-doc,
.file-icon-docx,
.file-icon-xls,
.file-icon-xlsx {
  color: #909399;
}

.grid-view {
  padding: 20px;
}

.grid-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 20px;
}

.grid-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.grid-item:hover {
  background-color: #f5f7fa;
}

.grid-item-name {
  margin-top: 8px;
  font-size: 14px;
  text-align: center;
  word-break: break-all;
}

.context-menu {
  position: fixed;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  padding: 5px 0;
  z-index: 1000;
}

.context-menu-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.context-menu-item:hover {
  background-color: #f5f7fa;
}

.preview-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

:deep(.el-dialog) {
  z-index: 3000 !important;
  margin-left: 200px !important;
  width: calc(100% - 300px) !important;
  position: absolute !important;
  left: 44% !important;
  transform: translateX(-50%) !important;
}

:deep(.el-dialog__wrapper) {
  z-index: 3000 !important;
}

:deep(.v-modal) {
  z-index: 2999 !important;
}

.preview-image {
  max-width: 100%;
  max-height: 70vh;
  object-fit: contain;
}

.preview-video {
  max-width: 100%;
  max-height: 70vh;
  width: 100%;
}

.preview-pdf,
.preview-office {
  width: 100%;
  height: 70vh;
  border: none;
}

.preview-audio {
  width: 100%;
  margin: 20px 0;
}

.preview-code {
  width: 100%;
  height: 70vh;
  overflow: auto;
  padding: 20px;
  background: #1e1e1e;
  border-radius: 4px;
  font-family: 'Consolas', 'Monaco', monospace;
}

.preview-code pre {
  margin: 0;
  white-space: pre-wrap;
}

.preview-code code {
  color: #d4d4d4;
  font-size: 14px;
  line-height: 1.5;
}

.preview-text {
  width: 100%;
  height: 70vh;
  overflow: auto;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;
  font-family: monospace;
}

.preview-unsupported {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  color: #909399;
}

.preview-unsupported .el-icon {
  font-size: 48px;
}

.share-dialog-content {
  padding: 20px 0;
}

.share-link {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.share-expiry {
  color: #909399;
  font-size: 14px;
}

.download-progress {
  padding: 20px;
}

.download-info {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  color: #606266;
  font-size: 14px;
}

.move-dialog-content {
  padding: 20px 0;
}

.current-path {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.folder-list {
  max-height: 300px;
  overflow-y: auto;
}

.folder-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px;
  cursor: pointer;
  transition: all 0.3s;
}

.folder-item:hover {
  background-color: #f5f7fa;
}

.folder-item .el-icon {
  color: #e6a23c;
}
</style> 